param(
    [Parameter(Mandatory=$true)]
    [string]$apiKey,

    [string]$ServiceName = "www",
    [string]$SourcePath = "dist/spa/*",
    [string]$OutputPath = "dist/$ServiceName.zip"
)

# API 配置
$apiUrl = "https://7us0nr0qw3.execute-api.eu-north-1.amazonaws.com/default/deploy_web_service"

# 1. 确保目标目录存在
$outputDir = Split-Path $OutputPath -Parent
if (-not (Test-Path $outputDir)) {
    New-Item -ItemType Directory -Path $outputDir | Out-Null
    Write-Host "Created directory: $outputDir"
}

# 2. 如果ZIP文件已存在则删除（解决文件已存在的问题）
if (Test-Path $OutputPath) {
    Write-Host "Removing existing ZIP file: $OutputPath"
    Remove-Item $OutputPath -Force
}

# 3. 使用.NET方法创建ZIP文件
Write-Host "Creating ZIP file: $OutputPath"
try {
    # 确保源文件存在
    $items = Get-Item $SourcePath -ErrorAction Stop

    # 添加.NET类型引用
    Add-Type -AssemblyName System.IO.Compression.FileSystem

    # 使用临时目录避免路径问题
    $tempDir = New-Item -ItemType Directory -Path (Join-Path $env:TEMP "tempzip_$(Get-Date -Format 'yyyyMMddHHmmss')") -Force

    # 复制文件到临时目录
    if ($items -is [array]) {
        foreach ($item in $items) {
            Copy-Item -Path $item.FullName -Destination $tempDir.FullName -Recurse -Force
        }
    } else {
        Copy-Item -Path $SourcePath -Destination $tempDir.FullName -Recurse -Force
    }

    # 创建ZIP文件
    [System.IO.Compression.ZipFile]::CreateFromDirectory($tempDir.FullName, $OutputPath)
    Write-Host "ZIP file created successfully"

    # 清理临时目录
    Remove-Item $tempDir.FullName -Recurse -Force -ErrorAction SilentlyContinue
}
catch {
    Write-Host "ZIP creation failed: $_" -ForegroundColor Red
    exit 1
}

# 4. 读取ZIP文件
Write-Host "Reading ZIP file: $OutputPath"
try {
    $zipBytes = [System.IO.File]::ReadAllBytes((Resolve-Path $OutputPath))
    Write-Host "File size: $($zipBytes.Length) bytes"
}
catch {
    Write-Host "Error reading ZIP file: $_" -ForegroundColor Red
    exit 1
}

# 5. 验证ZIP文件头
$headerValid = $true
if ($zipBytes.Length -ge 4) {
    if ($zipBytes[0] -ne 0x50 -or $zipBytes[1] -ne 0x4B -or $zipBytes[2] -ne 0x03 -or $zipBytes[3] -ne 0x04) {
        Write-Host "Error: Generated ZIP file has invalid header signature" -ForegroundColor Red
        Write-Host "Header: $($zipBytes[0..3] | ForEach-Object { '0x{0:X2}' -f $_ })"
        $headerValid = $false
    }
} else {
    Write-Host "Error: ZIP file is too small or empty" -ForegroundColor Red
    $headerValid = $false
}

if (-not $headerValid) {
    exit 1
}

# 6. 构建请求URL
$fullUrl = $apiUrl + "?service_name=" + [System.Uri]::EscapeDataString($ServiceName) + "&apiKey=" + [System.Uri]::EscapeDataString($apiKey)

# 7. 发送请求
Write-Host "Uploading to API Gateway: $fullUrl"
try {
    $response = Invoke-RestMethod -Uri $fullUrl -Method Post -Body $zipBytes -ContentType 'application/zip'

    Write-Host "Success: $($response.message)"
    Write-Host "S3 Path: $($response.s3Path)"
    Write-Host "Download URL: $($response.downloadUrl)" -ForegroundColor Green
    Write-Host "Expires in: 15 minutes"
}
catch {
    Write-Host "Request failed: $($_.Exception.Message)" -ForegroundColor Red

    if ($null -ne $_.Exception.Response) {
        $responseStream = $_.Exception.Response.GetResponseStream()
        $responseStream.Position = 0
        $reader = New-Object System.IO.StreamReader($responseStream)
        $responseBody = $reader.ReadToEnd()

        Write-Host "HTTP Status: $($_.Exception.Response.StatusCode)"
        Write-Host "Response body: $responseBody"
    }
}
